package com.lb.shopguide.ui.fragment.boss.market;

import android.graphics.Color;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.AdapterTemplateType;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.entity.market.TemplateTypeBean;
import com.lb.shopguide.event.boss.AdviceRefreshEvent;
import com.lb.shopguide.event.boss.ShowTipEvent;
import com.lb.shopguide.event.guide.BossSecretaryEvent;
import com.lb.shopguide.http.method.ApiMethodBoss;
import com.lb.shopguide.util.json.JsonUtil;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.BindView;

public class FragmentMarketTemplate extends BaseCommonFragment implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    private View view;
    private TextView tvAdviceText;
    private RelativeLayout layoutAdvice;

    private ArrayList<TemplateTypeBean> mTemplateTypeBeanList;

    private AdapterTemplateType mAdapterTemplate;

    public static FragmentMarketTemplate newInstance() {
        return new FragmentMarketTemplate();
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_market_template;
    }

    @Override
    public void initData() {
        mTemplateTypeBeanList = new ArrayList<>();
        sendRequestGetTemplateList();
        EventBus.getDefault().register(this);
    }

    @Override
    public void initView() {
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeColors(Color.rgb(253, 91, 89));

        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapterTemplate = new AdapterTemplateType(R.layout.item_template_type, mTemplateTypeBeanList);
        mRecyclerView.setAdapter(mAdapterTemplate);

        view = LayoutInflater.from(mContext).inflate(R.layout.layout_template_header, (ViewGroup) mRecyclerView.getParent(), false);
        layoutAdvice = view.findViewById(R.id.rl_advice);
        tvAdviceText = view.findViewById(R.id.tv_advice_text);
        addHeaderView();

        initListener();
    }

    private void initListener() {
        mAdapterTemplate.setOnUseTemplateClickListener(new AdapterTemplateType.OnUseTemplateClickListener() {
            @Override
            public void onUseTemplateClick(String templateCode, String templateName) {
                ((FragmentMarketing) getParentFragment()).start(FragmentUseTemplate.newInstance(templateCode, templateName, null, null));
            }
        });
    }

    @Override
    public void finishRefresh() {
        mSwipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void sessionOutOfDate() {

    }

    @Override
    public void requestError(String error) {

    }

    @Override
    public String getPageTag() {
        return FragmentMarketTemplate.class.getName();
    }

    @Override
    public void onRefresh() {
        mAdapterTemplate.setEnableLoadMore(false);
        if (mError) {
            mAdapterTemplate.setEmptyView(errorView);
            mError = false;
        } else {
            if (mNoData) {
                mAdapterTemplate.setEmptyView(noDataView);
                mNoData = false;
            } else {
                refresh();
            }
        }
    }

    private void addHeaderView() {
        sendRequestHasAdvices();
        layoutAdvice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((FragmentMarketing) getParentFragment()).start(FragmentActivityAdvice.newInstance());
            }
        });
        mAdapterTemplate.addHeaderView(view);
    }

    private void sendRequestHasAdvices() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    Boolean flag = (Boolean) response.getReturnContent();
                    if (flag) {
                        tvAdviceText.setText("您有新的活动建议，点击立即查看");
                        EventBus.getDefault().post(new ShowTipEvent(true));
                    } else {
                        tvAdviceText.setText("活动建议");
                        EventBus.getDefault().post(new ShowTipEvent(false));
                    }
                }
            }
        };
        ApiMethodBoss.hasNewActivitySuggestion(new SimpleLbObserver(listener, otherListener), this, FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestGetTemplateList() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    if (response.getReturnContent() != null) {
                        JsonArray jsonArrayTemplateType = JsonUtil.getJsonArrayFromMap(response.getReturnContent());
                        if (jsonArrayTemplateType.size() != 0) {
                            for (JsonElement obj : jsonArrayTemplateType) {
                                TemplateTypeBean bean = JsonUtil.getGson().fromJson(obj, TemplateTypeBean.class);
                                mTemplateTypeBeanList.add(bean);
                            }
                            mAdapterTemplate.setNewData(mTemplateTypeBeanList);
                        } else {
                            bindEmpty();
                        }
                        finishRefresh();
                    }
                }
            }
        };
        ApiMethodBoss.listTemplate(new SimpleLbObserver(listener, otherListener), this, FragmentEvent.DESTROY_VIEW);
    }

    public void refresh() {
        mTemplateTypeBeanList = new ArrayList<>();
        sendRequestGetTemplateList();
    }

    private void bindEmpty() {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshAdvice(AdviceRefreshEvent event) {
        sendRequestHasAdvices();
        EventBus.getDefault().post(new BossSecretaryEvent());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

}
